package com.xyzwps.harbor.service;

import com.xyzwps.harbor.model.UserPassword;
import com.xyzwps.harbor.repo.UserPasswordRepository;

import static com.xyzwps.harbor.util.HarborException.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

@Service
public class PasswordService {

    @Autowired
    private UserPasswordRepository userPasswordRepository;

    @Autowired
    private PasswordCrypto passwordCrypto;

    public Mono<Void> createPassword(long userId, String password) {
        var up = new UserPassword();
        up.setUserId(userId);
        up.setEncryptedPassword(passwordCrypto.encrypt(userId, password));
        return userPasswordRepository.insert(up);
    }

    public Mono<Boolean> isMatchedPassword(long userId, String realPassword) {
        return userPasswordRepository.selectByUserId(userId)
                .switchIfEmpty(Mono.error(notImplEx("password dose not exist." )))
                .map(userPassword -> passwordCrypto.check(userPassword, realPassword));
    }
}